CMU 15-112: Fundamentals of Programming and Computer Science
Day6 Practice (Due never)
- These problems will help you prepare for hw5 and quiz2.
- Do not use recursion.
- Do not hardcode the test cases in your solutions.
Code Tracing
What will this code print? Figure it out by hand, then run the code to confirm. Then slightly edit the code and try again.
- Trace #1:
import copy def ct1(a): b = a c = copy.copy(a) d = copy.deepcopy(a) a = a + [ 10 ] b[1][0] = "one" c[0] = "two" d[0].extend(d[1]) d[1][1] = 12 print("a:", a) print("b:", b) print("c:", c) print("d:", d) e = [ [ 2, 4 ], [ 6, 8 ] ] ct1(e) print("e:", e)
- Trace #2:
import copy def ct2(a): b = a c = copy.copy(a) d = copy.deepcopy(a) c[0][0] = "I" b[0][1] = "luv" b[1] = [3, 4] c[1][0] = "dogs" d[1] = d[0] d[1].pop() c[0].insert(2, "112") b.append("cats") print("a =", a) print("b =", b) print("c =", c) print("d =", d) z = [ ["yes", "no"], [35, 42] ] ct2(z) print("z =", z)
Free Response (Problem-Solving)
- Some Worked Examples Using Lists:
- makeMagicSquare(n)
Write the function makeMagicSquare(n) that takes a positive odd integer n and returns an nxn magic square by following De La Loubere's Method as described here. If n is not a positive odd integer, return None. - isLatinSquare(a)
Write the function isLatinSquare(a) that takes a 2d list and returns True if it is a Latin square and False otherwise. - isKnightsTour(a)
Background: A "knight's tour in chess is a sequence of legal knight moves such that the knight visits every square exactly once. We can represent a (supposed) knight's tour as an NxN list of the integers from 1 to N2 listing the positions in order that the knight occupied on the tour. If it is a legal knight's tour, then all the numbers from 1 to N2 will be included and each move from k to (k+1) will be a legal knight's move. With this in mind, write the function isKnightsTour(board) that takes such a 2d list of integers and returns True if it represents a legal knight's tour and False otherwise. - nQueensChecker(a)
Background: The "N Queens" problem asks if we can place N queens on an NxN chessboard such that no two queens are attacking each other. For most values of N, there are many ways to solve this problem. Here, you will write the function nQueensChecker(board) that takes a 2d list of booleans where True indicates a queen is present and False indicates a blank cell, and returns True if this NxN board contains N queens all of which do not attack any others, and False otherwise.